<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;

class CreateProjectModelCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'project:model {project} {modelName} {--m : 是否创建迁移文件}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '创建API集群项目模型: project:model 项目名 模型名 --m（可选，创建迁移文件）';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    protected function getStub()
    {
        return __DIR__ . '/stubs/project/model.stub';
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $args = $this->arguments();

        // 首次创建项目
        if (!is_dir(app_path('project/' . ucfirst($args['project']) . '/Models'))) {
            @mkdir(app_path('project/' . ucfirst($args['project'])), 0755, true);
            @mkdir(app_path('project/' . ucfirst($args['project']) . '/Models'), 0755, true);
        }

        $migrate = $option = $this->option('m');

        // NameSpace
        $namespace = 'Project\\' . ucfirst($args['project']) . '\\Models';

        // Class name
        $class_name =  ucfirst($args['project']) . '\\' . ucfirst($args['modelName']);

        // File name
        $file_name = ucfirst($args['project']) . ucfirst($args['modelName']) . '.php';

        // File path
        $logic_file = app_path() . '/Project/' . ucfirst($args['project']) . '/Models/' . $file_name;

        // File dir
        $logic_path = dirname($logic_file);

        //获取模板,替换变量
        $template = file_get_contents(dirname(__FILE__) . '/stubs/project/model.stub');
        $source = str_replace('[namespace]', $namespace, $template);
        $source = str_replace('[class_name]', ucfirst($args['project']) . ucfirst($args['modelName']), $source);

        //是否已存在相同文件
        if (file_exists($logic_file)) {
            $this->error('模型文件已存在');
            exit;
        }

        //创建
        if (file_exists($logic_path) === false) {
            if (mkdir($logic_path, 0755, true) === false) {
                $this->error('目录 <' . $logic_path . '> 没有写入权限');
                exit;
            }
        }

        //写入
        if (!file_put_contents($logic_file, $source)) {
            $this->error('创建失败！');
            exit;
        }

        // 创建 migrate
        if ($migrate) {
            $this->call("make:migration", [
                'name' => 'Create' . ucfirst($args['project']) . ucfirst(Str::plural($args['modelName'])) . 'Table',
            ]);
        }

        $this->info('创建成功！');
    }
}
